<?php


namespace App\Model\Logic;

use App\Helper\RedisConst;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * 用户关系
 * Class RelationShipLogic
 * @package App\Model\Logic
 */
class RelationShipLogic
{

    /**
     * @Inject("redis1.pool")
     * @var Pool
     */
    private $redis;

    /**
     * --------------------------------------------------------------------------
     * 批量获取用户关系信息
     * --------------------------------------------------------------------------
     * @param $login
     * @param $member_ids
     * @return mixed
     */
    public function multiMembership($login, $member_ids)
    {
        $func = function($pipe) use($login, $member_ids){
            $key = RedisConst::FOLLOWING . $login;
            foreach($member_ids as $member_id){
                $pipe->ZREVRANK($key, $member_id);
            }
            foreach($member_ids as $member_id){
                $k = RedisConst::FOLLOWING . $member_id;
                $pipe->ZREVRANK($k, $login);
            }
        };
        $res = $this->redis->pipeline($func);
        $part = count($res) / 2;
        $ship = [];
        for($i = 0; $i < $part; $i++){
            $k = $member_ids[$i];
            $m1 = $res[$i];
            $m2 = $res[$i+$part];
            if(is_numeric($m1) && is_numeric($m2)){
                $ship[$k] =  2; continue;
            }
            if(is_numeric($m1) && !is_numeric($m2)){
                $ship[$k] =  1; continue;
            }
            if(!is_numeric($m1) && !is_numeric($m2)) {
                $ship[$k] = 0; continue;
            }
        }
        return $ship;
    }


    //获取当前登录用户和其他用户的关注关系（2.0版本出现3种关系）
    public function membership($uid, $other_id, $is_following = false)
    {
        $u_ship = self::newisFollowed($uid, $other_id);
        $o_ship = 0;
        if($is_following) $o_ship = self::newisFollowed($other_id, $uid);
        if(!$u_ship) return 0; // 未关注
        // 双方互相关注
        if($u_ship && $o_ship && $is_following == true) return 2;
        return 1;  // 已关注
    }


    public function newisFollowed($uid, $followed_id)
    {
        $key = RedisConst::FOLLOWING.$uid;
        $is_exsit =  $this->redis->exsits($key);
        if(!$is_exsit) return 0;
        $rank =  $this->redis->zREVRANK($key, $followed_id);
        return is_numeric($rank) ? 1 : 0;
    }

}